package com.example.pathtracker.activity

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.maps.offlinemap.OfflineMapCity
import com.amap.api.maps.offlinemap.OfflineMapManager
import com.amap.api.maps.offlinemap.OfflineMapProvince
import com.amap.api.maps.offlinemap.OfflineMapStatus
import com.example.pathtracker.R
import java.util.concurrent.ConcurrentHashMap

class OfflineMapActivity : AppCompatActivity(), OfflineMapManager.OfflineMapDownloadListener {
    private lateinit var offlineMapManager: OfflineMapManager
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: CityAdapter
    private var cityList: MutableList<OfflineMapCity> = mutableListOf()
    private val progressMap = ConcurrentHashMap<String, Int>()
    private val stateMap = ConcurrentHashMap<String, Int>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_offline_map)
        supportActionBar?.title = "离线地图管理"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        checkAndRequestStoragePermission()

        recyclerView = findViewById(R.id.rv_city)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))

        offlineMapManager = OfflineMapManager(this, this)
        loadZhejiangCities()
    }

    override fun onResume() {
        super.onResume()
        loadZhejiangCities()
    }

    private fun checkAndRequestStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1001)
            }
        }
    }

    private fun loadZhejiangCities() {
        val provinces: List<OfflineMapProvince> = offlineMapManager.offlineMapProvinceList
        val zhejiang = provinces.find { it.provinceName.contains("浙江") }
        cityList = zhejiang?.cityList?.toMutableList() ?: mutableListOf()
        // 初始化进度和状态
        cityList.forEach {
            progressMap[it.city] = it.getcompleteCode()
            stateMap[it.city] = it.state
        }
        adapter = CityAdapter(cityList)
        recyclerView.adapter = adapter
    }

    override fun onDownload(progress: Int, state: Int, cityName: String?) {
        if (cityName != null) {
            val idx = cityList.indexOfFirst { it.city == cityName }
            val cityCode = cityList.getOrNull(idx)?.getcompleteCode()
            Log.d("OfflineMap", "onDownload: $cityName, progress=$progress, state=$state, idx=$idx, city.completeCode=$cityCode")
            progressMap[cityName] = progress
            stateMap[cityName] = state
            if (idx >= 0) {
                runOnUiThread { adapter.notifyItemChanged(idx) }
            } else {
                runOnUiThread { adapter.notifyDataSetChanged() }
            }
            if (state == OfflineMapStatus.SUCCESS) {
                Toast.makeText(this, "$cityName 下载完成", Toast.LENGTH_SHORT).show()
            }
        }
    }
    override fun onCheckUpdate(p0: Boolean, p1: String?) {}
    override fun onRemove(p0: Boolean, p1: String?, p2: String?) {
        runOnUiThread { adapter.notifyDataSetChanged() }
    }

    inner class CityAdapter(private val cities: List<OfflineMapCity>) : RecyclerView.Adapter<CityAdapter.CityViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CityViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_offline_city, parent, false)
            return CityViewHolder(view)
        }
        override fun getItemCount(): Int = cities.size
        override fun onBindViewHolder(holder: CityViewHolder, position: Int) {
            val city = cities[position]
            holder.bind(city)
        }
        inner class CityViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val tvName: TextView = itemView.findViewById(R.id.tv_city_name)
            private val tvSize: TextView = itemView.findViewById(R.id.tv_city_size)
            private val progressBar: ProgressBar = itemView.findViewById(R.id.progress_bar)
            private val btnDownload: Button = itemView.findViewById(R.id.btn_download)
            private val btnPause: Button = itemView.findViewById(R.id.btn_pause)
            private val btnDelete: Button = itemView.findViewById(R.id.btn_delete)
            fun bind(city: OfflineMapCity) {
                tvName.text = city.city
                tvSize.text = String.format("%.2f MB", city.size / 1024f)
                progressBar.max = 100
                val progress = progressMap[city.city] ?: city.getcompleteCode()
                val state = stateMap[city.city] ?: city.state
                if (state == OfflineMapStatus.SUCCESS) {
                    progressBar.progress = 100
                } else {
                    progressBar.progress = progress
                }
                when (state) {
                    OfflineMapStatus.SUCCESS -> {
                        btnDownload.visibility = View.GONE
                        btnPause.visibility = View.GONE
                        btnDelete.visibility = View.VISIBLE
                    }
                    OfflineMapStatus.LOADING -> {
                        btnDownload.visibility = View.GONE
                        btnPause.visibility = View.VISIBLE
                        btnDelete.visibility = View.VISIBLE
                    }
                    OfflineMapStatus.PAUSE -> {
                        btnDownload.visibility = View.VISIBLE
                        btnPause.visibility = View.GONE
                        btnDelete.visibility = View.VISIBLE
                    }
                    else -> {
                        btnDownload.visibility = View.VISIBLE
                        btnPause.visibility = View.GONE
                        btnDelete.visibility = View.GONE
                    }
                }
                btnDownload.setOnClickListener {
                    offlineMapManager.downloadByCityName(city.city)
                    Toast.makeText(this@OfflineMapActivity, "开始下载 ${city.city}", Toast.LENGTH_SHORT).show()
                }
                btnPause.setOnClickListener {
                    offlineMapManager.pauseByName(city.city)
                    Toast.makeText(this@OfflineMapActivity, "已暂停 ${city.city}", Toast.LENGTH_SHORT).show()
                }
                btnDelete.setOnClickListener {
                    offlineMapManager.remove(city.city)
                    Toast.makeText(this@OfflineMapActivity, "已删除 ${city.city}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
} 